package com.wongoing.apiclient.alipay.app;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayObject;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayFundTransOrderQueryModel;
import com.alipay.api.domain.AlipayFundTransToaccountTransferModel;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.request.AlipayFundTransOrderQueryRequest;
import com.alipay.api.request.AlipayFundTransToaccountTransferRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayFundTransOrderQueryResponse;
import com.alipay.api.response.AlipayFundTransToaccountTransferResponse;
import com.wongoing.util.LogService;

import io.netty.util.internal.StringUtil;

public class AlipayHelper {

	private static AlipayHelper instance;
	
	public AlipayHelper() {
		super();
		// TODO Auto-generated constructor stub
	}
	
	//单例模式
	public synchronized static AlipayHelper getInstance() {
		if(instance==null) {
			instance = new AlipayHelper();
		}
		return instance;
	}
	
	/**
	 * 功能说明：App支付宝支付统一下单接口
	 * 修改说明：
	 * @author 吴兆强
	 * @date 2017年12月28日 下午3:25:37
	 * @param WIDout_trade_no 商户订单号
	 * @param WIDtotal_amount 总金额
	 * @param WIDsubject 订单标题
	 * @param WIDbody 订单描述
	 * @param notify_url 异步通知
	 * @param resturnUrl 通不通知
	 * @param ip ip
	 * @param WIDShowUrl 商品显示URL
	 * @return 
	 * @throws AlipayApiException
	 */
	public String payResult(String WIDout_trade_no, String WIDtotal_amount, String WIDsubject, String WIDbody,
			String notify_url, String resturnUrl)
			throws AlipayApiException {
		AlipayClient client = new DefaultAlipayClient(AlipayConfig.URL, AlipayConfig.APPID,AlipayConfig.RSA_PRIVATE_KEY, AlipayConfig.FORMAT, AlipayConfig.CHARSET, AlipayConfig.ALIPAY_PUBLIC_KEY,AlipayConfig.SIGNTYPE);
		AlipayTradeWapPayRequest alipay_request = new AlipayTradeWapPayRequest();
		// 封装请求支付信息
		AlipayTradeWapPayModel model = new AlipayTradeWapPayModel();
		model.setOutTradeNo(WIDout_trade_no);
		model.setSubject(WIDsubject);
		model.setTotalAmount(WIDtotal_amount);
		model.setBody(WIDbody);
		model.setTimeoutExpress("10m");
		model.setProductCode(AlipayConfig.PRODUCT_CODE);
		alipay_request.setBizModel(model);
		// 设置异步通知地址
		alipay_request.setNotifyUrl(notify_url);
		// 设置同步地址
		alipay_request.setReturnUrl(resturnUrl);
		String sHtmlText = client.pageExecute(alipay_request).getBody();
		return sHtmlText;
	}

	/**
	 * 功能说明：使用deeplink方式调起支付宝APP,appId必须是20000125
	 * 修改说明：String deeplink = "alipays://platformapi/startApp?appId=20000125&orderSuffix=" + token
	 *			+ "#Intent;scheme=alipays;package=com.eg.android.AlipayGphone;end";
	 * @author 吴兆强
	 * @date 2018年6月20日 上午9:38:47
	 * @param WIDout_trade_no 商户订单号
	 * @param WIDtotal_amount  总金额
	 * @param WIDsubject 商品标题
	 * @param WIDbody 商品描述
	 * @param notify_url 异步通知url
	 * @param resturnUrl 同步通知url
	 * @return
	 */
	public String goAliPayAppDeeplinkStr(String WIDout_trade_no, String WIDtotal_amount, String WIDsubject, String WIDbody){
		try {
			String html = payResult(WIDout_trade_no, WIDtotal_amount.toString(), WIDsubject, WIDbody, AlipayConfig.notify_url, "");
			Document document = Jsoup.parse(html);
			Element input = document.select("input[name]").get(0);
			Element form = document.select("form[action]").get(0);
			String value = input.attr("value");
			String action = form.attr("action");
			Connection con = Jsoup.connect(action).userAgent("Mozilla/5.0 (Linux; Android 6.0.1; MX4 Build/MOB30M; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/51.0.2704.106 Mobile Safari/537.36");
			con.data(input.attr("name"), value);
			Document doc = con.post();
			String token = "";
			String deeplink = "";
			//使用正则爬去网页中指定数据
			Matcher m = Pattern.compile("(h5_route_token=\\\\\".+?&is_h5_route=\\\\\"true\\\\\")").matcher(doc.html());
			if(!m.find()) 
				return null; 
			System.out.println(m.group(0));
			token = m.group(0).replaceAll("=", "%3D").replaceAll("&", "%26").replaceAll("\"", "").replaceAll("\\\\", "");
			if(token==null || "".equals(token)) 
				return null;
			deeplink+="alipays://platformapi/startApp?appId=20000125&orderSuffix=";
			deeplink+=token;
			deeplink+="#Intent;scheme=alipays;package=com.eg.android.AlipayGphone;end";
			LogService.getInstance().debug("支付宝deeplink解析成功："+deeplink);
			return deeplink.trim();
		} catch (Exception e) {
			LogService.getInstance().debug("支付宝deeplink解析失败：",e);
		}
		return null;
	}
	
	/**
	 * 功能说明：转账业务
	 * 修改说明：
	 * @author 吴兆强
	 * @date 2018年6月27日 下午7:49:14
	 * @param outBizNo
	 * @param payeeType
	 * @param payeeAccount
	 * @param amount
	 * @param payerShowName
	 * @param payeeRealName
	 * @param remark
	 * @return
	 * @throws AlipayApiException
	 */
	public AlipayFundTransToaccountTransferResponse payTransferResult(String outBizNo, String payeeType, String payeeAccount, String amount, 
			String payerShowName, String payeeRealName, String remark) throws AlipayApiException {
		//初始化客户端
		AlipayClient client = new DefaultAlipayClient(AlipayConfig.URL, 
				AlipayConfig.APPID,AlipayConfig.RSA_PRIVATE_KEY, 
				AlipayConfig.FORMAT, AlipayConfig.CHARSET, 
				AlipayConfig.ALIPAY_PUBLIC_KEY,
				AlipayConfig.SIGNTYPE);
		//初始化单笔转账到支付宝账户请求
		AlipayFundTransToaccountTransferRequest alipayRequest  =  new AlipayFundTransToaccountTransferRequest();
		//初始化参数实体类
		AlipayFundTransToaccountTransferModel entity = new AlipayFundTransToaccountTransferModel();
		entity.setOutBizNo(outBizNo);
		entity.setPayeeType(payeeType);
		entity.setPayeeAccount(payeeAccount);
		entity.setAmount(amount);
		if(StringUtils.isNotBlank(payerShowName)) 
			entity.setPayerShowName(payerShowName);
		if(StringUtils.isNotBlank(payeeRealName))
			entity.setPayeeRealName(payeeRealName);
		if(StringUtils.isNotBlank(remark))
			entity.setRemark(remark);
		alipayRequest.setBizModel(entity);
		AlipayFundTransToaccountTransferResponse  response  = client.execute(alipayRequest);
		return response ;
	}
	
	/**
	 * 功能说明：转账业务查询
	 * 修改说明：
	 * @author 吴兆强
	 * @date 2018年6月27日 下午10:52:00
	 * @param outBizNo 商户订单号
	 * @param orderId 支付宝返回订单号
	 * @return
	 * @throws AlipayApiException
	 */
	public AlipayFundTransOrderQueryResponse payTransferQueryResult(String outBizNo, String orderId) throws AlipayApiException {
		//初始化客户端
		AlipayClient client = new DefaultAlipayClient(AlipayConfig.URL, 
				AlipayConfig.APPID,AlipayConfig.RSA_PRIVATE_KEY, 
				AlipayConfig.FORMAT, AlipayConfig.CHARSET, 
				AlipayConfig.ALIPAY_PUBLIC_KEY,
				AlipayConfig.SIGNTYPE);
		AlipayFundTransOrderQueryRequest request = new AlipayFundTransOrderQueryRequest();
		AlipayFundTransOrderQueryModel entity = new AlipayFundTransOrderQueryModel();
		if(StringUtils.isNotBlank(orderId)) 
			entity.setOrderId(orderId);
		if(StringUtils.isNotBlank(outBizNo)) 
			entity.setOutBizNo(outBizNo);
		request.setBizModel(entity);
		AlipayFundTransOrderQueryResponse response = client.execute(request);
		return response;
	}

}
